package org.gephi.statistics.spi.path;

import java.io.BufferedWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class PathWritingThread implements Runnable {

	Logger logger = LogManager.getLogger();
	ConcurrentLinkedQueue<String> queue;
	BufferedWriter bufWriter;
	boolean Flag = true;

	public PathWritingThread(BufferedWriter bufWriter, ConcurrentLinkedQueue<String> queue) {
		this.bufWriter = bufWriter;
		this.queue = queue;
	}

	@Override
	public void run() {
		while (Flag) {// 循环监听
			try {
				Thread.sleep(30000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (!queue.isEmpty()) {
				String tmp = "";
				String line = "";
				HashSet<String> tmpSet = new HashSet<String>();
				while ((line = queue.poll()) != null) {
					tmpSet.add(line.trim());
				}
				for (String s : tmpSet) {
					tmp += s + "\n";
				}
				tmp = tmp.substring(0, tmp.lastIndexOf("\n"));
				synchronized (this.bufWriter) {
					try {
						logger.info(tmp);
						this.bufWriter.write(tmp);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	public void setFlag(boolean flag) {
		this.Flag = flag;
	}

}
